<?php
//check login
include('include/conf.php');
require_once 'include/reader.php';
//begin selection of clienti
//verifica autentificarea
$id_connect = connect_to_database(HOST, USER, PASS, 'server_imei2');
$sesiune = mysql_real_escape_string($_GET['sesiune']);
$str = "SELECT tip_cont FROM clienti WHERE sesiune = '$sesiune'";
$result = mysql_query($str,$id_connect);
$num_rows = mysql_num_rows($result);
if($num_rows==1){
	$value = mysql_fetch_assoc($result);
	$tip_cont = $value['tip_cont'];
	if($tip_cont != 'admin'){
	    echo "operation not permited!";
			exit();
	}
}else{
  echo "login first";
	exit();
}
//begin prelucrare upload from client
$target_path = $_SERVER['DOCUMENT_ROOT']."/";
$target_path = $target_path.basename( $_FILES['Filedata']['name']);
if(move_uploaded_file($_FILES['Filedata']['tmp_name'], $target_path)) {
    echo "The file ".  basename( $_FILES['Filedata']['name']). 
    " has been uploaded";
} else{
    echo "There was an error uploading the file, please try again!";
}
//begin read file
$data = new Spreadsheet_Excel_Reader();
$data->setOutputEncoding('CP1251');
//$data->read('extraction.xls');
$data->read($target_path);
for ($i = 2; $i <= $data->sheets[0]['numRows']; $i++) {
	//indice 1=nume, 2=imei, 3=unlock, 6=cost. Acces data $data->sheets[0]['cells'][$i][$j]
	//se cauta fiecare imei pentru care exista cod de unlock in baza de date
	$unlock = $data->sheets[0]['cells'][$i][3];
	if($unlock != ""){
    //begin update data
    $imei = $data->sheets[0]['cells'][$i][2];
    $data_out = time();
    //verifica if unlock is unknow
    if(strtolower($unlock) == "unknow"){
      //reface credit
      //mai intai afla pretul
      $str = "SELECT nume, cost FROM coduri WHERE imei='$imei'";
      $result = mysql_query($str,$id_connect);
      $value = mysql_fetch_assoc($result);
      $cost = $value['cost'];
      $nume = $value['nume'];
      //refacere cont
      $str = "UPDATE clienti SET cr_consumat=cr_consumat-$cost, cr_ramas=cr_ramas+$cost WHERE nume='$nume'";
      mysql_query($str,$id_connect);
      //set cost egal cu zero
      $cost = 0;
      $str = "UPDATE coduri SET unlock_code='$unlock', data_out='$data_out', status='done', cost='$cost' WHERE imei='$imei'";
    }else{
      $str = "UPDATE coduri SET unlock_code='$unlock', data_out='$data_out', status='done' WHERE imei='$imei'";
    }    
    mysql_query($str,$id_connect);
  }
}
//when finish delete file
unlink($target_path);
?>
